package com.wangyadong.hobby.metric.gauge.lession4;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/12/1816:21
 **/
public class RatioGaugeExample {

    private static final MetricRegistry metricRegistry = new MetricRegistry();

    private static final ConsoleReporter consoleReporter = ConsoleReporter.
            forRegistry(metricRegistry).
            convertRatesTo(TimeUnit.SECONDS).
            convertDurationsTo(TimeUnit.SECONDS).
            build();
    private static final Meter totalMeter = new Meter();
    private static final Meter successMeter = new Meter();

    public static void main(String[] args) {


        consoleReporter.start(10, TimeUnit.SECONDS);
        metricRegistry.gauge("success-rate", () -> new RatioGauge() {
            @Override
            protected Ratio getRatio() {
                return Ratio.of(successMeter.getCount(), totalMeter.getCount());
            }
        });

        for (; ; ) {
            randomSleep();
            business();
        }

    }


    private static void business() {
        //total inc
        totalMeter.mark();
        try {
            int x = 1 / ThreadLocalRandom.current().nextInt(6);
            //inc
            successMeter.mark();
        } catch (Exception e) {
            //
            e.printStackTrace();
        }
    }


    private static void randomSleep() {
        try {
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(6));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
